# database/models.py（修正后）
from pydantic import BaseModel
import json

class PushTemplate(BaseModel):
    first: str
    keyword1: str
    keyword2: str
    keyword3: str
    remark: str

class PushTask(BaseModel):
    id: int
    tempmsg: str
    app_open_id: str
    
    @property
    def template_data(self) -> PushTemplate:
        """解析tempmsg中的模板数据"""
        try:
            data = json.loads(self.tempmsg)
            # 获取第一个非url的键
            template_key = next((k for k in data if k != "url"), None)
            if template_key:
                return PushTemplate(**data[template_key])
            return PushTemplate(first="", keyword1="", keyword2="", keyword3="", remark="")
        except json.JSONDecodeError:
            print(f"JSON解析错误: {self.tempmsg}")
            # 修正：删除重复的keyword3参数
            return PushTemplate(first="解析失败", keyword1="", keyword2="", keyword3="", remark="")
    
    @property
    def url(self) -> str:
        """获取跳转URL"""
        try:
            data = json.loads(self.tempmsg)
            return data.get("url", "")
        except json.JSONDecodeError:
            return ""